package com.gzdh.dishrecognition.ui.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.StringUtils;
import com.dhkj.web.utils.MyObserverRes;
import com.dhkj.web.utils.RequestUtils;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.greendao.dao.MacMainpSbruanDinnerEntityDao;
import com.gzdh.dishrecognition.AppContext;
import com.gzdh.dishrecognition.R;
import com.gzdh.dishrecognition.config.ProductConst;
import com.gzdh.dishrecognition.config.SysConstConfig;
import com.gzdh.dishrecognition.emu.OfflineGetCardSnTypeEmus;
import com.gzdh.dishrecognition.emu.PeripheralDeviceEmus;
import com.gzdh.dishrecognition.emu.ReadCardTypeEmus;
import com.gzdh.dishrecognition.entity.MacMainpSbruanDinnerEntity;
import com.gzdh.dishrecognition.event.CartEvent;
import com.gzdh.dishrecognition.event.TimeEvent;
import com.gzdh.dishrecognition.model.ProductCartModel;
import com.gzdh.dishrecognition.ui.activity.ScanTakeFoodActivity;
import com.gzdh.dishrecognition.ui.activity.SelectPayActivity;
import com.gzdh.dishrecognition.ui.adapter.LeftBmcmAdapter;
import com.gzdh.dishrecognition.ui.pre.ShowCardPre;
import com.gzdh.dishrecognition.util.ByteUtil;
import com.gzdh.dishrecognition.util.ProductSUtils;
import com.gzdh.dishrecognition.util.SystemUtils;
import com.jiebao.nfc.uartnfc.CardReaderDevice;
import com.jiebao.util.CardReaderUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class FixedNumberView extends LinearLayout {

    private final Cache<String,String> cache = CacheBuilder.newBuilder().maximumSize(1000).
            expireAfterWrite(3, TimeUnit.SECONDS).build();
    private final Context mContext;

    private TextView netStatusRv;

    private TextView timeTv;

    private TextView priceTv;

    private TextView payBut;

    private RecyclerView bmcmRv;

    private TextView amountTv;

    private ImageView scanTakeBtn;

    private ShowCardPre showCardPre;

    public void setShowCardPre(ShowCardPre showCardPre) {
        this.showCardPre = showCardPre;
    }

    private final MacMainpSbruanDinnerEntityDao macMainpSbruanDinnerEntityDao = AppContext.getInstance().getDaoSession().getMacMainpSbruanDinnerEntityDao();

    public FixedNumberView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.view_mode_fixed_number, this, true);
        mContext = context;
        initView();
        initDate();
    }

    public void clear() {
        mProductCartModel = new ProductCartModel();
        mProductCartModelList = new ArrayList<>();
        ProductConst.getInstance().setProductCartModelList(new ArrayList<>());
    }

    @SuppressLint("SetTextI18n")
    public void init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        if (SysConstConfig.getInstance().isAllowCard()) {
            if(SysConstConfig.getInstance().getPeripheralDeviceModel() == PeripheralDeviceEmus.defaultType) {
                CardReaderDevice.getInstance().initCardReader();
            }
        }
        clear();
        if (ProductConst.getInstance().getProductCartModelList().size() == 0) {
            priceTv.setText("￥" + SysConstConfig.getInstance().getFixedAmount());
        }
    }

    private void initView() {
        EventBus.getDefault().register(this);
        netStatusRv = findViewById(R.id.netStatusRv);
        timeTv = findViewById(R.id.timeTv);
        priceTv = findViewById(R.id.tv_price);
        payBut = findViewById(R.id.payBut);
        //bmcmRv = findViewById(R.id.bmcmRv);
        amountTv = findViewById(R.id.amountTv);

        //扫码领餐
        scanTakeBtn = findViewById(R.id.scanTakeBtn);
        if(!SysConstConfig.getInstance().isScanTake()) {
            scanTakeBtn.setVisibility(View.GONE);
        }
        scanTakeBtn.setOnClickListener(view -> {
            if(cache.getIfPresent("scanTake") != null) {
                return;
            }
            cache.put("scanTake", String.valueOf(System.currentTimeMillis()));
            ScanTakeFoodActivity.start(mContext);
        });
    }

    LeftBmcmAdapter leftBmcmAdapter;

    private ProductCartModel mProductCartModel = new ProductCartModel();
    private List<ProductCartModel> mProductCartModelList = new ArrayList<>();

    @SuppressLint("SetTextI18n")
    private void initDate() {
        priceTv.setText("￥" + SysConstConfig.getInstance().getFixedAmount());
        payBut.setOnClickListener(view -> {
            String price = this.priceTv.getText().toString().substring(1);
            if(new android.icu.math.BigDecimal(price).compareTo(new android.icu.math.BigDecimal(0)) <= 0) {
                Toast.makeText(mContext,"请确认支付金额", Toast.LENGTH_SHORT).show();
                return;
            }
            String cacheValue = cache.getIfPresent("isSubmit");
            if(cacheValue != null) {
                return;
            }
            cache.put("isSubmit", String.valueOf(System.currentTimeMillis()));
            mProductCartModel = new ProductCartModel();
            /*MacMainpSbruanDinnerEntity dinnerEntity = leftBmcmAdapter.getDinner();
            if (dinnerEntity != null) {
                mProductCartModel.setDinner(dinnerEntity.getDinner());
            } else {
                mProductCartModel.setDinner("");
            }*/
            mProductCartModel.setZl("9");
            mProductCartModel.setNumber(1);
            mProductCartModel.setName("现金菜");
            mProductCartModel.setPrice(this.priceTv.getText().toString().substring(1));
            mProductCartModel.setBm("xjc");
            mProductCartModelList.add(mProductCartModel);
            ProductConst.getInstance().setProductCartModelList(mProductCartModelList);
            EventBus.getDefault().post(new CartEvent());
            SelectPayActivity.startAct(mContext);
        });
        
        leftBmcmAdapter = new LeftBmcmAdapter(mContext);
        List<MacMainpSbruanDinnerEntity> macMainpSbruanDinnerEntityList = macMainpSbruanDinnerEntityDao.loadAll();
        ProductSUtils.setSbruanDinnerName(macMainpSbruanDinnerEntityList);
        leftBmcmAdapter.setList(macMainpSbruanDinnerEntityList);

        GridLayoutManager bmcmManager = new GridLayoutManager(mContext, 4);
        bmcmManager.setOrientation(RecyclerView.VERTICAL);
        /*bmcmRv.setLayoutManager(bmcmManager);
        bmcmRv.setAdapter(leftBmcmAdapter);
        bmcmRv.addItemDecoration(new MyGridSpacingItemDecoration(3));*/

//        leftBmcmAdapter.setUserOnClick(bmcmEntity -> selectBmcm(bmcmEntity));
    }

    public void close() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        CardReaderDevice.getInstance().deInitCardReader();
    }

    private long lastTime = 0;

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(TimeEvent event) {
        @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        timeTv.setText("当前时间：" + simpleDateFormat.format(new Date()));
        if (lastTime == 0) {
            String cardNo = CardReaderDevice.getInstance().readCardNo();
            if (!StringUtils.isEmpty(cardNo)) {
                lastTime = System.currentTimeMillis();
                byte[] cardSnTemp = ByteUtil.hexStringToByte(cardNo.toUpperCase());
                String cardSn = cardNo.toUpperCase();
                if(SysConstConfig.getInstance().getOfflineGetCardSnType() == OfflineGetCardSnTypeEmus.reverse) {
                    byte[] b = new byte[4];
                    for (int i = 0; i < cardSnTemp.length; i++) {
                        b[i] = cardSnTemp[3 - i];
                    }
                    cardSn = ByteUtil.bytesToHexString(b);
                }

                if (SysConstConfig.getInstance().getReadCardType() == ReadCardTypeEmus.cardSQ) {
                    System.out.println("读取块" + ((SysConstConfig.getInstance().getCardDataSector() * 4) + 1));
                    System.out.println("读取的密码：" + CardReaderUtils.byteArray2HexString(SysConstConfig.getInstance().getCardSectorPass().getPassword(cardSnTemp)));
                    byte[] bReturn = CardReaderDevice.getInstance().readM1CardChunkData(0, ((SysConstConfig.getInstance().getCardDataSector() * 4) + 1),
                            SysConstConfig.getInstance().getCardSectorPass().getPassword(cardSnTemp));
                    if (bReturn != null) {
                        Log.e("TAG", "bReturn " + (SysConstConfig.getInstance().getCardDataSector() * 4)
                                + " length " + bReturn.length + " " + CardReaderUtils.byteArray2HexString(bReturn));
                        String khby1 = CardReaderUtils.byte2HexString(bReturn[0]);
                        String khby2 = CardReaderUtils.byte2HexString(bReturn[1]);
                        String khby3 = CardReaderUtils.byte2HexString(bReturn[2]);
                        int kha = Integer.parseInt(khby1, 16);
                        int khb = Integer.parseInt(khby2, 16);// 涉及到金额都要转码
                        int khc = Integer.parseInt(khby3, 16);
                        int kh = kha * 0x10000 + khb * 0x100 + khc; // 金额转码 写卡要转回来
                        System.out.println("获取卡号：" + kh);
                    } else {
                        System.out.println("方式为空");
                        return;
                    }
                }

                RequestUtils.getFk(mContext, SystemUtils.getSerialNumber(), cardSn, new MyObserverRes<>(mContext, false) {
                    @Override
                    public void onSuccess(JSONObject result) {
                        String stringBuffer = "姓名：" + result.getString("name") + "  /  自购：" + result.getString("kye") + "  /  补贴:" + result.getString("btye");
                        if (showCardPre != null) {
                            showCardPre.showCard(result.getString("kye"), result.getString("btye"));
                        }
                    }

                    @Override
                    public void onFailure(Throwable e, String errorMsg) {
                        if(e != null && e.getCause() != null) {
                            if(e.getCause().toString().contains("java.net.ConnectException")) {
                                errorMsg = "网络异常,请切换离线状态读卡";
                            }
                        }
                    }
                });
            }
        } else if (System.currentTimeMillis() - lastTime > 5000) {
            lastTime = 0;
            if (showCardPre != null) {
                showCardPre.hide();
            }
        }
    }

    public void resShow() {
        amountTv.setText(String.format("合计：%s", ProductConst.getInstance().getProductCartPrice()));
        if(!SysConstConfig.getInstance().isScanTake()) {
            scanTakeBtn.setVisibility(View.GONE);
        } else {
            scanTakeBtn.setVisibility(View.VISIBLE);
        }
    }

    public void connectedNet() {
        netStatusRv.setText("已联网");
        netStatusRv.setBackgroundResource(R.color.green);
        netStatusRv.setTextColor(getResources().getColor(R.color.white));
    }

    public void disConnectedNet() {
        netStatusRv.setText("未联网");
        netStatusRv.setBackgroundResource(R.color.red);
        netStatusRv.setTextColor(getResources().getColor(R.color.white));
    }
}
